package com.qingzhu.controller.shopserver;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.pojo.ShopCart;
import com.qingzhu.pojo.ShopOption;
import com.qingzhu.pojovo.ResultVo;
import com.qingzhu.service.ShopOptionService;
import com.qingzhu.service.impl.ShopOptionServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@WebServlet("/cart/update")
public class UpdateCartController extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    ShopOptionService shopOptionService = new ShopOptionServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("购物车更新服务..");
        // 读取购物车信息
        String json = req.getReader().readLine();
        Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
        // 将购物车信息提取出来
        ShopCart shopCart = objectMapper.readValue(objectMapper.writeValueAsString(map.get("shopCart")), ShopCart.class);
        // 效验购物车中的商品信息是否有足够的库存
        shopCart = shopOptionService.updateShopSption(shopCart);

        // 获取cookie信息（弃用方案）
        Cookie[] cookies = req.getCookies();
        if (cookies == null) {
            System.out.println("检测到浏览器对cookie的支持可能不稳定...将自动切换到token技术");
        }
        // 更新cookie（兼容cookie技术）
        updateCookie(resp,shopCart);
        System.out.println("修改预览："+shopCart);
        resp.getWriter().write(objectMapper.writeValueAsString( new ResultVo(200,shopCart)));
    }


    /* 更新cookie */
    public void updateCookie (HttpServletResponse resp, ShopCart shopCart) throws IOException {
        // 将购物车序列化成json串
        String cartJson = objectMapper.writeValueAsString(shopCart);
        // 将购物车的信息编码后再储存，否则可能会抛出不合法的字符异常
        String encodeCart = URLEncoder.encode(cartJson, "UTF-8");
        /* 更新cookie */
        Cookie cookie = new Cookie("cart", encodeCart);
        resp.addCookie(cookie);
    }
}
